package Interview.Amazon;

import java.util.Stack;

/**
 * @author leiwenkang <leiwenkang@kuaishou.com>
 * Created on 2022-07-25
 */
public class Test06流水线 {
    public static void main(String[] args) {
        int[] array = {34,16,8,9};
        int[] result = buildPackage(array);

        for (int i = 0; i < result.length; i++) {
            System.out.println(result[i]);
        }

    }

    private static int[] buildPackage(int[] array) {
        if (array == null || array.length == 0) {
            return new int[0];
        }

        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < array.length; i++) {
            int value = array[i];
            while (!stack.isEmpty() && stack.peek() < value) {
                value += stack.pop();
            }
            stack.push(value);
        }

        int[] result = new int[stack.size()];
        for (int i = stack.size() - 1; i >= 0; i--) {
            result[i] = stack.pop();
        }

        return result;
    }
}
